import type { AdvancedSearch, FindOverload, InfoOverload, PageInfo, PageOverload, PagedResult } from "@/models/advaned-search";
import { ApiFetch } from "./api-fetch";

export class ApiBase extends ApiFetch {
  add = async <T>(model: any) => await this.post<T>("", model);

  addAll = async <T>(models: any[]) => await this.post<T>("batch", models);

  edit = async <T>(id: number, model: any) => await this.put<T>(`${id}`, model);

  remove = async <T>(id: number) => await this.delete<T>(`${id}`);

  removeAll = async <T>(ids: number[]) => await this.delete<T>("batch/" + ids.toString());

  findById = async <T>(id: number) => await this.get<T>(`${id}`);

  info: InfoOverload = async <T extends object>(params?: URLSearchParams | AdvancedSearch<T>) => {
    let url = "info";
    if (params) url = params instanceof URLSearchParams ? `${url}?${params}` : `${url}/${encodeURI(JSON.stringify(params))}`;
    return await this.get<T>(url);
  };

  find: FindOverload = async <T extends object>(params?: URLSearchParams | AdvancedSearch<T>) => {
    let url = "find";
    if (params) url = params instanceof URLSearchParams ? `${url}?${params}` : `${url}/${encodeURI(JSON.stringify(params))}`;
    return await this.get<T[]>(url);
  };

  page: PageOverload = async <T extends object>(params?: URLSearchParams | AdvancedSearch<T>, pager?: PageInfo) => {
    let url = `${pager?.currentPage || 1}/${pager?.pageSize || 20}`;
    if (params) url = params instanceof URLSearchParams ? `${url}?${params}` : `${url}/${encodeURI(JSON.stringify(params))}`;
    return await this.get<PagedResult<T>>(url);
  };
}
